package com.util;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.portlet.PortletRequest;
import javax.servlet.http.HttpSession;

import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.shopping.NoSuchCartException;
import com.liferay.portlet.shopping.model.ShoppingCart;
import com.liferay.portlet.shopping.model.ShoppingItem;
import com.liferay.portlet.shopping.service.ShoppingCartLocalServiceUtil;
import com.liferay.portlet.shopping.service.ShoppingItemLocalServiceUtil;
import com.slayer.model.CartItem;
import com.slayer.model.ShoppingItemExt;
import com.slayer.service.ShoppingCartExtLocalServiceUtil;
import com.slayer.service.ShoppingItemExtLocalServiceUtil;

public class CartUtil {

	public static ShoppingCart getCart(ThemeDisplay themeDisplay) {
		return getCart(themeDisplay.getUser(), themeDisplay.getScopeGroupId());
	}

	public static ShoppingCart getCart(User user, long scopeGroupId) {

		ShoppingCart shoppingCart = null;

		if (Validator.isNull(user))
			return null;

		try {
			shoppingCart = ShoppingCartLocalServiceUtil.getCart(
					user.getUserId(), scopeGroupId);
		} catch (PortalException e) {
			if (e instanceof NoSuchCartException) {

				long cartId = 0l;
				try {
					cartId = CounterLocalServiceUtil.increment();
				} catch (SystemException e2) {
					e2.printStackTrace();
				}
				shoppingCart = ShoppingCartLocalServiceUtil
						.createShoppingCart(cartId);
				shoppingCart.setUserId(user.getUserId());
				shoppingCart.setUserName(user.getFullName());
				shoppingCart.setGroupId(scopeGroupId);
				shoppingCart.setCompanyId(user.getCompanyId());
				shoppingCart.setCreateDate(new java.util.Date());
				try {
					shoppingCart = ShoppingCartLocalServiceUtil
							.updateShoppingCart(shoppingCart);
				} catch (SystemException e1) {
					e1.printStackTrace();
				}
			}
		} catch (SystemException e) {
			e.printStackTrace();
		}
		return shoppingCart;
	}

	@SuppressWarnings("unchecked")
	public static void addToCart(PortletRequest portletRequest) {

		long itemId = ParamUtil.getLong(portletRequest, "itemId");

		if (itemId <= 0l)
			return;

		HttpSession session = PortalUtil.getHttpServletRequest(portletRequest)
				.getSession();
		Map<Long, CartItem> items = (HashMap<Long, CartItem>) session
				.getAttribute("USER_CART_ITEMS");

		if (Validator.isNull(items)) {
			items = new HashMap<Long, CartItem>();
			session.setAttribute("USER_CART_ITEMS", items);
		}
		
		int qty = ParamUtil.getInteger(portletRequest, "qty");
		int frequency = ParamUtil.getInteger(portletRequest, "frequency");
		double amount = ParamUtil.getDouble(portletRequest, "amount");
		CartItem cartItem = null;
				
		ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest
				.getAttribute(WebKeys.THEME_DISPLAY);


		// if the user is signed in
		if (themeDisplay.isSignedIn()) {
			System.out.println("if the user is signed in");
			ShoppingCart shoppingCart = CartUtil.getCart(themeDisplay);
			shoppingCart.setModifiedDate(new java.util.Date());
			try {
				ShoppingCartLocalServiceUtil.updateShoppingCart(shoppingCart);
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cartItem = new CartItem(qty, amount, frequency);
			ShoppingCartExtLocalServiceUtil.persistCartExt(itemId, shoppingCart.getCartId(), cartItem);
		}
		
			if (!items.containsKey(itemId)) {
			cartItem = new CartItem(qty, amount, frequency);
			items.put(itemId, cartItem);
		} else {
			cartItem = items.get(itemId);
			cartItem.setAmount(cartItem.getAmount() + amount);
			cartItem.setQty(cartItem.getQty() + qty);
			cartItem.setFrequency(frequency);
		}

		boolean variableAmount = false;
		try {
			ShoppingItem shoppingItem = ShoppingItemLocalServiceUtil
					.fetchShoppingItem(itemId);
			if (Validator.isNotNull(shoppingItem)
					&& shoppingItem.getPrice() == 0.0) {
				variableAmount = true;
			}
		} catch (SystemException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		if (variableAmount) {
			cartItem.setQty(qty);
		}
	}

	public static Map<Integer, String> getFrequencyMap(long itemId) {

		Map<Integer, String> frequencyMap = new TreeMap<Integer, String>();

		ShoppingItemExt itemExt = null;
		try {
			itemExt = ShoppingItemExtLocalServiceUtil
					.fetchShoppingItemExt(itemId);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		char[] frequencyOptionsArray = { '1', '1', '1', '1', '1' };
		if (Validator.isNotNull(itemExt)) {
			String frequencyOptions = itemExt.getFrequency();

			if (Validator.isNotNull(frequencyOptions)
					&& frequencyOptions.length() == 5) {
				frequencyOptionsArray = frequencyOptions.toCharArray();
			}
		}

		for (int i = 0; i < frequencyOptionsArray.length; i++) {
			if (frequencyOptionsArray[i] == '1') {
				frequencyMap.put(IConstants.FREQUENCY_ARRAY[i],
						IConstants.FREQUENCY[i]);
			}
		}

		return frequencyMap;
	}
}